from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import traceback
from threading import Thread
import json


# 配置 ChromeDriver 路径，替换为你的 ChromeDriver 路径，你也可以将chromedriver拖入文件根目录，使用'./chromedriver.exe'路径。
chrome_driver_path = 'D:/software/chromedriver-win64/chromedriver.exe'


def http_response_monitor(chrome_driver: WebDriver, param_request_id):
    chrome_driver.execute_cdp_cmd('Network.enable', {})
    print("http request id:", param_request_id)
    # 监听网络事件
    response = chrome_driver.execute_cdp_cmd(
        'Network.getResponseBody',
        {'requestId': param_request_id}
    )
    print(response)


# 初始化 ChromeDriver Service
service = Service(chrome_driver_path)
# 打开浏览器时的相关配置，可以根据需求进行打开和关闭
options = Options()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")  # 启动时最大化窗口
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
driver = webdriver.Chrome(service=service, options=options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
# 打开百度首页
driver.get("https://blog.51cto.com/u_16213427/12658226")
time.sleep(5)
logs = driver.get_log("performance")
for log in logs:
    print(log)
    message = json.loads(log['message'])
    if message is None:
        continue
    second_message = message.get("message")
    if second_message is None:
        continue
    request_method = second_message.get('method')
    if request_method is None:
        continue
    if request_method != 'Network.responseReceived':
        continue
    params = second_message.get('params')
    if params is None:
        continue
    if params.get('type') != 'Fetch':
        continue
    request_id = None
    try:
        request_id = params.get('requestId')
    except Exception as e:
        print(f"An error occurred: {e}")
        traceback.TracebackException()
    if request_id is None:
        continue
    print(request_id)
    http_response_monitor(driver, request_id)


